package com.easyaccount.service;

import com.easyaccount.bean.DeptVO;
import com.easyaccount.commons.CommonResp;
import com.easyaccount.commons.TablePage;
import com.easyaccount.dao.DeptMapper;
import com.easyaccount.exception.BizException;
import com.easyaccount.model.Dept;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeptService {

    @Resource
    private DeptMapper deptMapper;

    public CommonResp save(Dept dept){
        int count1 = deptMapper.selectByNameCount(dept.getDeptName());
        if(count1 > 0) throw new BizException("部门名称已存在",444);

        int count2 = deptMapper.selectByCodeCount(dept.getDeptCode());
        if (count2 > 0) throw new BizException("部门编码已存在",444);

        int i = deptMapper.insertSelective(dept);
        if (i == 0) throw new BizException("添加失败",444);

        return CommonResp.success();
    }

    public CommonResp update(Dept dept){
        int count1 = deptMapper.selectByIdAndNameCount(dept);
        if(count1 > 0) throw new BizException("部门名称已存在",444);

        int count2 = deptMapper.selectByIdAndCodeCount(dept);
        if (count2 > 0) throw new BizException("部门编码已存在",444);


        int i = deptMapper.updateByPrimaryKeySelective(dept);
        if (i == 0) throw new BizException("添加失败",444);

        return CommonResp.success();
    }

    public CommonResp delete(Dept dept){
        Dept result = deptMapper.selectByPrimaryKey(dept.getDeptId());
        if(result == null) throw new BizException("部门不存在",444);

        List<Dept> depts = deptMapper.selectByParentId(dept.getParentId());
        if (depts != null && depts.size() > 0) throw new BizException("该部门下面存在子部门，无法删除",444);

        int i = deptMapper.deleteByPrimaryKey(dept.getDeptId());
        if (i == 0) throw new BizException("删除失败",444);

        return CommonResp.success();
    }

    public TablePage searchByName(TablePage tablePage, String deptName){
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;

        List<DeptVO> deptVOs = new ArrayList<>();
        List<Dept> depts = deptMapper.selectByName(start, size, deptName);
        for (Dept dept : depts) {
            DeptVO deptVO = new DeptVO();
            BeanUtils.copyProperties(dept,deptVO);
            Dept p = deptMapper.selectByPrimaryKey(dept.getParentId());
            if (p != null) deptVO.setParentName(p.getDeptName());
            deptVOs.add(deptVO);
        }

        int count = deptMapper.selectByNameCount(deptName);
        tablePage.setCount(count);
        tablePage.setData(deptVOs);
        return tablePage;
    }

    public CommonResp list(){
        List<Dept> depts = deptMapper.selectAll();
        return CommonResp.success(depts);
    }

}
